﻿// COPYRIGHT (C) Markeluo ALL RIGHTS RESERVED. 
// GITEE: https://gitee.com/luowanli/AntdUI 
// QQ: 563944808

using AntdUI;
using Dm;
using Furion;
using IMES.BLL;
using IMES.Entity;
using IMES.Page.SysRoleUser;
using IMES.VO;
using Mapster;
using System.ComponentModel;
using System.Windows.Forms;

namespace IMES.Page
{
    public partial class UC_SysRoleUser : BasePage
    {
        RoleRep roleRep = App.GetService<RoleRep>();
        MenuRep menuRep = App.GetService<MenuRep>();
        UserRep userRep = App.GetService<UserRep>();
        BindingList<SysRoleVO> rolesData = new BindingList<SysRoleVO>();
        BindingList<SysUserVO> usersData = new BindingList<SysUserVO>();

        public UC_SysRoleUser()
        {
            InitializeComponent();
        }

        public override bool InitData()
        {
            list_role.Columns = new AntdUI.ColumnCollection {
                new AntdUI.ColumnCheck("check").SetFixed().SetWidth("50"),
                new AntdUI.Column("btns", "操作").SetFixed().SetWidth("150").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Name", "角色").SetWidth("150").SetLocalizationTitleID("Table.Column."),
                new AntdUI.ColumnCheck("IsAdmin", "是否管理员").SetAutoCheck(false).SetWidth("120").SetColAlign().SetLocalizationTitleID("Table.Column."),
                new AntdUI.ColumnCheck("Usable", "状态").SetAutoCheck(false).SetFixed().SetWidth("80").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Remark", "备注", AntdUI.ColumnAlign.Center).SetWidth("auto").SetLocalizationTitleID("Table.Column."),
            };

            list_user.Columns= new AntdUI.ColumnCollection {
                new AntdUI.ColumnCheck("check").SetFixed().SetWidth("50"),
                new AntdUI.Column("btns", "操作").SetFixed().SetWidth("150").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("UserCode", "账号").SetWidth("150").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("UserName", "姓名").SetWidth("120").SetColAlign().SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("RoleName", "角色").SetWidth("180").SetColAlign().SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Mobile", "手机号").SetWidth("120").SetColAlign().SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("CreateTime", "更新时间").SetWidth("150").SetColAlign().SetLocalizationTitleID("Table.Column."),
                new AntdUI.ColumnCheck("Usable", "状态").SetAutoCheck(false).SetFixed().SetWidth("80").SetLocalizationTitleID("Table.Column."),
                new AntdUI.Column("Remark", "备注", AntdUI.ColumnAlign.Center).SetWidth("auto").SetLocalizationTitleID("Table.Column."),
            };

            //加载数据
            RefreshData();

            return base.InitData();
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private void RefreshData()
        {
            //角色
            List<SysRoleVO> roles = roleRep.GetList().Adapt<List<SysRoleVO>>();
            rolesData = new BindingList<SysRoleVO>(roles);
            list_role.Binding(rolesData);

            //用户：
            List<SysUserVO> users= userRep.AllUserList().Adapt<List<SysUserVO>>();
            usersData = new BindingList<SysUserVO>(users);
            list_user.Binding(usersData);
        }

        /// <summary>
        /// 角色管理 按钮事件处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void menuBar_role_MenuBarClickEvent(BaseMenuBarButtonType type, object sender, EventArgs args)
        {
            switch (type)
            {
                case BaseMenuBarButtonType.Add:
                    AddRoleClick(sender, args);
                    break;
                case BaseMenuBarButtonType.Del:
                    DelRoleClick(sender, args);
                    break;
            }
        }

        private void AddRoleClick(object sender, EventArgs args)
        {
            frm_RoleEditor editor = new frm_RoleEditor();
            if (!editor.InitData([])) return;
            DialogResult rlt = editor.ShowDialog();
            if (rlt != DialogResult.OK) return;
            //刷新数据显示 
            rolesData.Add(editor.EditModel!);
        }

        private void DelRoleClick(object sender, EventArgs args)
        {
            var list = rolesData.Where(x => x.check).ToList();
            if (list != null && list.Count > 0) { }
            else
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this.Parent!.FindForm()!, "提示", "请选择需要删除的项后再试!", AntdUI.TType.Warn)
                {
                    OnButtonStyle = (id, btn) =>
                    {
                        btn.BackExtend = "135, #6253E1, #04BEFE";
                    },
                    CancelText = null,
                    OkText = "确定"
                });
                return;
            }

            var rlt = AntdUI.Modal.open(this.Parent!.FindForm()!, "删除确认", $"确认删除选择的 {list.Count}个角色 ?");
            if (rlt != DialogResult.OK) return;

            //var rlt = AntdUI.Modal.open(this.Parent!.FindForm()!, "删除确认", $"确认删除角色 {rowdata.Name} ?");
        }

        /// <summary>
        /// 用户管理 按钮事件处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void menuBar_user_MenuBarClickEvent(BaseMenuBarButtonType type, object sender, EventArgs args)
        {
            switch (type)
            {
                case BaseMenuBarButtonType.Add:
                    AddUserClick(sender, args);
                    break;
                case BaseMenuBarButtonType.Del:
                    DeUserClick(sender, args);
                    break;
            }
        }

        private void DeUserClick(object sender, EventArgs args)
        {
            //删除用户
               
        }

        private void AddUserClick(object sender, EventArgs args)
        {
            //新增用户
            frm_UserEditor editor = new frm_UserEditor();
            if (!editor.InitData([])) return;
            DialogResult rlt = editor.ShowDialog();
            if (rlt != DialogResult.OK) return;
            //刷新数据显示 
            usersData.Add(editor.EditModel!);
        }

        private void list_role_CellButtonClick(object sender, AntdUI.TableButtonEventArgs e)
        {
            if (e.Btn.Id == "edit")
            {
                var rowdata = list_role.SortList()[e.RowIndex - 1];

                frm_RoleEditor editor = new frm_RoleEditor();
                if (!editor.InitData([rowdata])) return;
                DialogResult rlt = editor.ShowDialog();
                if (rlt != DialogResult.OK) return;
                //刷新数据显示
                rowdata = editor.EditModel!;
            }
            if (e.Btn.Id == "delete")
            {
                SysRoleVO rowdata = (SysRoleVO)list_role.SortList()[e.RowIndex - 1];
                var rlt = AntdUI.Modal.open(this.Parent!.FindForm()!, "删除确认", $"确认删除角色 {rowdata.Name} ?");
                if (rlt != DialogResult.OK) return;

                var delRlt = roleRep.Delete(rowdata.Adapt<Role>());
                if (delRlt)
                {
                    rolesData.Remove(rowdata);
                    AntdUI.Message.success(this.Parent!.FindForm()!, "删除成功!", Font);
                }
            }
        }

        private SysRoleVO? SelectRole = null;
        private void list_role_SelectIndexChanged(object sender, EventArgs e)
        {
            var selIndex = list_role.SelectedIndex;
            if (selIndex <= 0) return;

            if (IsRoleAuth)
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this.Parent!.FindForm()!, "提示", "请先保存/取消角色菜单授权!", AntdUI.TType.Warn)
                {
                    OnButtonStyle = (id, btn) =>
                    {
                        btn.BackExtend = "135, #6253E1, #04BEFE";
                    },
                    CancelText = null,
                    OkText = "确定"
                });
                return;
            }

            SelectRole = (SysRoleVO)list_role.SortList()[selIndex - 1];
            RefreshRoleMenus();
        }

        private void RefreshRoleMenus()
        {
            lblRole_Name.Text = SelectRole!.Name;
            var treeData = menuRep.GetMenuTree();
            var roleMenus = roleRep.GetMenusByRole(SelectRole!.Id);

            tree_menus.Items.Clear();
            tree_menus.Items.AddRange(formatTreeData(treeData, roleMenus));
            btn_RoleSave.Visible=true;
        }

        private List<TreeItem> formatTreeData(List<Entity.Menu> treeData, List<Entity.RoleMenu> authMenus)
        {
            List<TreeItem> items = new List<TreeItem>();
            if (treeData != null && treeData.Count > 0)
            {
                TreeItem newTreeNode = null;
                foreach (var item in treeData)
                {
                    newTreeNode = new TreeItem() { ID = item.No, Text = item.Title, Tag = item, Enabled = false };
                    int countNum = authMenus.Where(x => x.MenuNo == item.No).Count();
                    if (countNum > 0) newTreeNode.Checked = true;
                    items.Add(newTreeNode);

                    if (item.Childs != null && item.Childs.Count > 0)
                        AddMenuSub(newTreeNode, item.Childs, authMenus);
                }
            }
            return items;
        }

        private void AddMenuSub(TreeItem treeitem, List<Entity.Menu> items, List<Entity.RoleMenu> authMenus)
        {
            treeitem.Expand = true;
            treeitem.Sub.Clear();
            TreeItem newTreeNode = null;
            foreach (var item in items)
            {
                newTreeNode = new TreeItem() { ID = item.No, Text = item.Title, Enabled = false };
                int countNum = authMenus.Where(x => x.MenuNo == item.No).Count();
                if (countNum > 0) newTreeNode.Checked = true;

                treeitem.Sub.Add(newTreeNode);

                if (item.Childs != null && item.Childs.Count > 0)
                    AddMenuSub(newTreeNode, item.Childs, authMenus);
            }
        }

        private bool isRoleAuth = false;

        public bool IsRoleAuth 
        { 
            get => isRoleAuth;
            set
            {
                isRoleAuth = value;
                if (isRoleAuth)
                {
                    btn_RoleSave.Text = "保存";
                    btn_RoleSave.IconSvg = "CheckOutlined";
                    btn_RoleSave.Type = TTypeMini.Success;
                    btn_RoleCancel.Visible = true;

                    foreach(var item in tree_menus.Items)
                    {
                        EnableTreeNode(item,true);
                    }
                }
                else
                {
                    btn_RoleSave.Text = "编辑";
                    btn_RoleSave.IconSvg = "EditOutlined";
                    btn_RoleSave.Type = TTypeMini.Primary;
                    btn_RoleCancel.Visible = false;

                    foreach (var item in tree_menus.Items)
                    {
                        EnableTreeNode(item, false);
                    }
                }

            }
        }

        private void EnableTreeNode(TreeItem node,bool isEnable)
        {
            node.Enabled = isEnable;
            if (node.Sub != null && node.Sub.Count > 0) {
                foreach (TreeItem item in node.Sub)
                {
                    EnableTreeNode(item, isEnable);
                }
            }
        }

        private bool SaveRoleMenus()
        {
            bool bolNext = true;
            List<string> nodes= new List<string>();
            getCheckedMenuNos(tree_menus.Items, nodes);
            roleRep.SaveRoleMenus(SelectRole!.Id, nodes);

            return bolNext;
        }

        private void getCheckedMenuNos(TreeItemCollection treelist,List<string> checkedNos)
        {
            foreach (var item in treelist)
            {
                if (item.Checked)
                {
                    checkedNos.Add(item.ID!.ToString());
                }
                if(item.Sub!=null && item.Sub.Count > 0)
                {
                    getCheckedMenuNos(item.Sub, checkedNos);
                }
            }
        }

        private void btn_RoleSave_Click(object sender, EventArgs e)
        {
            if(SelectRole==null)
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this.Parent!.FindForm()!, "提示", "请先选择需要授权的角色后再试!", AntdUI.TType.Warn)
                {
                    OnButtonStyle = (id, btn) =>
                    {
                        btn.BackExtend = "135, #6253E1, #04BEFE";
                    },
                    CancelText = null,
                    OkText = "确定"
                });
                return;
            }

            if (!isRoleAuth)
            {
                IsRoleAuth = true;
            }
            else
            {
                //开始保存操作
                bool isNext= SaveRoleMenus();
                if (!isNext) return;

                AntdUI.Message.success(this.Parent!.FindForm()!, "保存成功!", Font);
                IsRoleAuth = false;
            }
        }

        private void btn_RoleCancel_Click(object sender, EventArgs e)
        {
            var rlt = AntdUI.Modal.open(this.Parent!.FindForm()!, "取消确认", $"确认取消角色 {SelectRole!.Name} 的授权操作?");
            if (rlt != DialogResult.OK) return;

            IsRoleAuth = false;
        }
    }
}
